﻿using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;

namespace OrderManager.DataAccess
{
    /// <summary>
    /// Provides connection to database
    /// </summary>
    public class UnitOfWork : IDisposable
    {
        /// <summary>
        /// Initializes a new instance of <see cref="OrderManager.DataAccess.UnitOfWork"/> class and opens connection using connection string that is specified in web.config
        /// </summary>
        public UnitOfWork()
        {
            Connection = new SqlConnection
                             {
                                 ConnectionString =
                                     ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString
                             };

            Connection.Open();
        }

        /// <summary>
        /// Gets current SqlConnection instance which can be set by default constuctor
        /// </summary>
        public SqlConnection Connection { get; private set; }


        #region IDisposable Members
        /// <summary>
        /// Closes connection if it is open
        /// </summary>
        public void Dispose()
        {
            if (Connection.State == ConnectionState.Open)
            {
                Connection.Close();
            }
        }

        #endregion
    }
}